from http.server import BaseHTTPRequestHandler, HTTPServer
import json
import sqlite3
import os
from storeSQL import initialize_database, store_books

# 定义HTTP请求处理程序
class BookRequestHandler(BaseHTTPRequestHandler):
    def do_POST(self):
        # 检查请求路径
        if self.path == '/add_books':
            content_length = int(self.headers['Content-Length'])
            post_data = self.rfile.read(content_length)
            
            try:
                # 将接收到的数据解析为JSON
                books_data = json.loads(post_data.decode('utf-8'))
                
                # 将书籍信息存储到数据库
                store_books(json.dumps(books_data))
                
                # 返回成功响应
                self.send_response(200)
                self.send_header('Content-type', 'application/json')
                self.end_headers()
                self.wfile.write(json.dumps({"message": "Books added successfully"}).encode('utf-8'))
            except Exception as e:
                # 返回错误响应
                self.send_response(400)
                self.send_header('Content-type', 'application/json')
                self.end_headers()
                self.wfile.write(json.dumps({"error": str(e)}).encode('utf-8'))
        else:
            # 返回404响应
            self.send_response(404)
            self.end_headers()

    def do_GET(self):
        # 检查请求路径
        if self.path.startswith('/query_books'):
            try:
                # 解析查询参数
                query = self.path.split('?')[-1]
                params = dict(param.split('=') for param in query.split('&'))
                
                # 构建SQL查询
                query_conditions = []
                query_values = []
                for key, value in params.items():
                    value = value.replace('%20', ' ').strip()  # Replace %20 with space and remove leading/trailing spaces
                    query_conditions.append(f"{key} LIKE ?")
                    query_values.append(f"%{value}%")
                sql_query = f"SELECT * FROM books WHERE {' AND '.join(query_conditions)}"
                print(f"Executing SQL Query: {sql_query} with values {query_values}")
                # 查询数据库
                db_path = os.path.join(os.path.dirname(__file__), '..', 'books.db')
                conn = sqlite3.connect(db_path)
                cursor = conn.cursor()
                cursor.execute(sql_query, query_values)
                rows = cursor.fetchall()
                conn.close()
                
                # 返回查询结果
                self.send_response(200)
                self.send_header('Content-type', 'application/json')
                self.end_headers()
                self.wfile.write(json.dumps({"books": rows}).encode('utf-8'))
            except Exception as e:
                # 返回错误响应
                self.send_response(400)
                self.send_header('Content-type', 'application/json')
                self.end_headers()
                self.wfile.write(json.dumps({"error": str(e)}).encode('utf-8'))
        else:
            # 返回404响应
            self.send_response(404)
            self.end_headers()

# 启动HTTP服务器
def run(server_class=HTTPServer, handler_class=BookRequestHandler, port=8080):
    initialize_database()  # 确保数据库已初始化
    server_address = ('', port)
    httpd = server_class(server_address, handler_class)
    print(f"Starting HTTP server on port {port}...")
    httpd.serve_forever()

if __name__ == "__main__":
    run()